<template>
  <div class="statement-balance-change">
    <!-- 余额变动记录 -->
    <div class="app-main-content-box">
      <app-main-title title="余额变动记录" />
      <!-- 变动说明 -->
      <div class="app-main-tips-box top-tips">
        <div class="title">
          <i class="el-icon-warning" /> 报表说明
        </div>
        <ul>
          <li>1.本报表是会员余额变动的所有记录，你可以通过筛选数据，得到自己对账或者数据分析所需的数据。</li>
        </ul>
      </div>
      <!--filter区域-->
      <div class="filter">
        <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
          <el-form-item
            label="选择时间："
            prop="date"
            :rules="[
              { required: true, message: '时间区间不能为空'}
            ]"
          >
            <el-date-picker
              v-model="filterForm.date"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
          <el-form-item label="业务单号：" prop="bizOrderNo">
            <el-input v-model="filterForm.bizOrderNo" placeholder="请输入业务单号" style="width:400px;" />
          </el-form-item>
          <!-- 筛选 -->
          <div class="app-main-filter-collapse-box">
            <el-collapse>
              <el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
                <el-form-item label="门店：" prop="shopId">
                  <el-select
                    v-model="filterForm.shopId"
                    filterable
                    placeholder="可通过名称搜索"
                    style="width:400px"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.user.allManageShopFilterOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="终端：" prop="deviceId">
                  <el-select
                    v-model="filterForm.deviceId"
                    filterable
                    placeholder="可通过终端名/终端编号搜索"
                    style="width:400px"
                  >
                    <template v-for="item in $store.state.user.allManageDeviceFilterOptions">
                      <el-option
                        v-if="filterForm.shopId === '' ||item.shopId == filterForm.shopId || item.kdDeviceNo ==''"
                        :key="item.id"
                        :label="
                          item.kdDeviceNo === ''
                            ? item.deviceName
                            : item.deviceName + '(' + item.kdDeviceNo + ')'
                        "
                        :value="item.kdDeviceNo"
                      />
                    </template>
                  </el-select>
                </el-form-item>

                <el-form-item label="变动类型：" prop="recordTypes">
                  <el-checkbox
                    v-model="checkAllRecordTypes"
                    :indeterminate="isIndeterminateRecordTypes"
                    class="fl check-all"
                    @change="handlecheckAllRecordTypesChange"
                  >全选</el-checkbox>
                  <el-checkbox-group
                    v-model="filterForm.recordTypes"
                    @change="handleCheckRecordTypeChange"
                  >
                    <el-checkbox
                      v-for="(item,index) in recordTypesCheckOptions"
                      :key="index"
                      :label="item.value"
                    >{{ item.label }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="业务类型：" prop="bizCode">
                  <el-radio-group v-model="filterForm.bizCode">
                    <el-radio label="all">全部</el-radio>
                    <el-radio
                      v-for="(item,index) in manageBizCodeOptions"
                      :key="index"
                      :label="item.key"
                    >{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="业务来源：" prop="sourceCode">
                  <el-radio-group v-model="filterForm.sourceCode">
                    <el-radio label="all">全部</el-radio>
                    <template v-for="(item, index) in sourceCodeOptions">
                      <el-radio :key="index" :label="item.key">{{ item.label }}</el-radio>
                    </template>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="支付方式：" prop="payment">
                  <el-radio-group v-model="filterForm.payment">
                    <el-radio label="all">全部</el-radio>
                    <el-radio
                      v-for="item in paymentOptions"
                      :key="item.key"
                      :label="item.key"
                    >{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
          </div>

          <el-form-item class="filter-btn">
            <el-button type="primary" round @click="submitForm('filterForm')">查 询</el-button>
            <el-button round @click="resetForm('filterForm')">重 置</el-button>
            <el-button
              v-if="!$store.getters.banBtnList.includes('BTN_BALANCE_CHANGE_DETAIL_EXPORT')"
              round
              @click="downExcel"
            >导 出</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--内容展示区域-->
      <div v-loading="tableLoading" class="content">
        <!-- 卡片 -->
        <div class="content-card">
          <el-row :gutter="10">
            <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
              <el-card>
                <TotalCard :data="cardData_1" />
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
              <el-card>
                <TotalCard :data="cardData_2" />
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
              <el-card>
                <TotalCard :data="cardData_3" />
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
              <el-card>
                <TotalCard :data="cardData_4" />
              </el-card>
            </el-col>
          </el-row>
        </div>
        <!-- 表格内容 -->
        <div class="list-table">
          <el-table size="small" :data="list" border stripe style="width: 100%" empty-text="暂无数据">
            <el-table-column prop="time" label="变动时间" fixed="left" width="150" />
            <el-table-column prop="bizOrderNo" label="业务单号" width="150" />
            <el-table-column prop="memberName" label="会员名称" />
            <el-table-column prop="memberCardType" label="卡类型" />
            <el-table-column prop="memberCardNo" label="卡号" />
            <el-table-column prop="recordType" label="变动类型" />
            <el-table-column prop="bizName" label="业务类型" />
            <el-table-column prop="sourceName" label="业务来源" />
            <el-table-column prop="payment" label="支付方式" />
            <el-table-column prop="balance" label="变动金额(元)">
              <template slot-scope="scope">
                <div v-if="Number(scope.row.balance)==0">{{ Number(scope.row.balance) }}</div>
                <div
                  v-else
                  :class="scope.row.balance>0?'app-text-color-danger':'app-text-color-success'"
                >{{ scope.row.balance>0?'+'+scope.row.balance:scope.row.balance }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="remainBalance" label="变动后总余额(元)" />
            <el-table-column prop="shopName" label="门店">
              <template slot-scope="scope">
                <span>{{ scope.row.shopName?scope.row.shopName:"总部" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="device" label="消费终端" />
            <el-table-column prop="operator" label="操作人" />
            <el-table-column prop="promoter" label="推广人" />
            <el-table-column prop="remark" label="业务备注" />
          </el-table>
          <!-- 分页 -->
          <pagination-direction
            v-if="paginationConfig.total!==0"
            :config="paginationConfig"
            @sizeschange="sizesChange"
            @pagechange="pageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getBalanceRecordsList,
  getBalanceRecordStatistic
} from '@/api/statement'
import { downBalanceChangeRecord } from '@/api/download'
import TotalCard from '../components/TotalCard.vue'
export default {
  components: {
    TotalCard
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        // 分页配置
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      recordTypesCheckOptions: [
        {
          label: '充值',
          value: 1
        },
        {
          label: '赠送',
          value: 2
        },
        {
          label: '消费',
          value: 3
        },
        {
          label: '退款',
          value: 4
        },
        {
          label: '扣除',
          value: 5
        }
      ],
      recordTypesOptions: [1, 2, 3, 4, 5],
      // 状态
      tableLoading: false, // 表格loading
      checkAllRecordTypes: true, // recordTypes 多选状态
      isIndeterminateRecordTypes: false, // recordTypes
      // 数据
      list: [], // 表格数据
      cardData_1: [
        '总充值',
        0,
        '日均充值',
        0,
        '总充值：所选择的筛选条件下顾客共充值的金额',
        '日均充值：总充值/选择日期区间天数'
      ], // 卡片一
      cardData_2: [
        '总赠送',
        0,
        '日均赠送',
        0,
        '总赠送：所选择的筛选条件下赠送给顾客的金额',
        '日均赠送：总赠送/选择日期区间天数'
      ], // 卡片二
      cardData_3: [
        '总消费',
        0,
        '日均消费',
        0,
        '总消费：所选择的筛选条件下顾客的消费金额和',
        '日均消费：总消费/选择日期区间天数'
      ], // 卡片三
      cardData_4: [
        '总退款',
        0,
        '日均退款',
        0,
        '总退款：所选择的筛选条件退还给顾客的款项和',
        '日均退款：总退款/选择日期区间天数'
      ], // 卡片四
      filterForm: {
        date: [
          this.$momentMini().format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        shopId: '',
        recordTypes: [1, 2, 3, 4, 5],
        bizOrderNo: '',
        deviceId: '',
        bizCode: 'all',
        sourceCode: 'all', // 订单来源
        payment: 'all'
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageBizCodeOptions',
      'sourceCodeOptions',
      'paymentOptions'
    ]),
    shopId() {
      return this.filterForm.shopId
    }
  },
  watch: {
    shopId(newValue, oldValue) {
      this.filterForm.deviceId = ''
    }
  },
  mounted() {
    this.$store.dispatch('GetManageDevice') // 获取终端
    this.fetchData() // 加载页面
  },
  methods: {
    /**
       *  获取数据
       */

    // 获取表格数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          const params = await this.setRequestParams()
          params.pageNum = page
          params.pageSize = pageSize
          this.tableLoading = true
          Promise.all([this.getTotal(params), this.getRecord(params)]).then(
            () => {
              this.tableLoading = false
            }
          )
        }
      })
    },

    // 获取请求筛选数据
    setRequestParams() {
      return new Promise((resolve, reject) => {
        const params = Object.assign({}, this.filterForm)
        params.beginTimestamp = this.$momentMini(params.date[0]).unix()
        params.endTimestamp = this.$momentMini(params.date[1]).unix()
        delete params.date
        // 清除多余字段
        for (const key in params) {
          if (params[key] === '' || params[key] === 'all') {
            delete params[key]
          }
        }
        resolve(params)
      })
    },

    // 获取统计
    getTotal(params) {
      return new Promise((resolve, reject) => {
        getBalanceRecordStatistic(params)
          .then((res) => {
            this.setCardTotal(res.data)
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取记录
    getRecord(params) {
      if (params.bizOrderNo) {
        delete params.beginTimestamp
        delete params.endTimestamp
      }
      return new Promise((resolve, reject) => {
        getBalanceRecordsList(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 赋值卡片
    setCardTotal(data) {
      console.log('赋值卡片 - setCardTotal', data)
      // 赋值卡片  充值 赠送 消费  退款
      this.cardData_1.splice(
        1,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.totalRecharge,
              2,
              false
            )
      )
      this.cardData_1.splice(
        3,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.dailyRecharge,
              2,
              false
            )
      )
      this.cardData_2.splice(
        1,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.totalGiven,
              2,
              false
            )
      )
      this.cardData_2.splice(
        3,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.dailyGiven,
              2,
              false
            )
      )
      this.cardData_3.splice(
        1,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.totalConsume,
              2,
              false
            )
      )
      this.cardData_3.splice(
        3,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.dailyConsume,
              2,
              false
            )
      )
      this.cardData_4.splice(
        1,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.totalRefund,
              2,
              false
            )
      )
      this.cardData_4.splice(
        3,
        1,
        '￥' +
            this.$options.filters.parseNumberToThousands(
              data.dailyRefund,
              2,
              false
            )
      )
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
       *  按钮组
       */
    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.checkAllRecordTypes = true // recordType 多选状态
      this.isIndeterminateRecordTypes = false // recordType
    },

    // 导出
    downExcel() {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          const params = await this.setRequestParams()
          downBalanceChangeRecord(params)
            .then((res) => {
              if (res.code === 0) {
                this.$alert(
                  '数据导出中，请稍后到数据下载中心进行下载',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    center: true,
                    type: 'success',
                    callback: (action) => {}
                  }
                )
              }
            })
            .catch((err) => {})
        }
      })
    },

    /**
       *  状态组
       */
    // checkAllRecordType多选状态
    handlecheckAllRecordTypesChange(val) {
      if (val) {
        this.filterForm.recordTypes = this.recordTypesOptions
        this.checkAllRecordTypes = true
      } else {
        this.filterForm.recordTypes = []
        this.checkAllRecordTypes = false
      }
      this.isIndeterminateRecordTypes = false
    },

    handleCheckRecordTypeChange(value) {
      const checkedLength = value.length
      const maxLength = this.recordTypesOptions.length
      this.checkAllRecordTypes = checkedLength === maxLength
      this.isIndeterminateRecordTypes =
          checkedLength > 0 && checkedLength < maxLength
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /* 头部说明 */
  .top-tips {
    margin-bottom: 20px;
  }

  /* 筛选 */
  .filter {
    .filter-btn {
      margin-bottom: 20px;
    }
    .check-all {
      margin-right: 30px;
    }
    .el-select {
      width: 120px;
    }
    .input-with-select {
      width: 400px;
    }
    // 充值单选换行
    .el-radio + .el-radio {
      margin-left: 0;
    }
    .el-radio {
      margin-right: 10px;
      height: 32px;
      line-height: 32px;
    }
  }

  /* 内容 */
  .content {
    &-card {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }
</style>
